package com.qrback.controller;

import com.qrback.entity.Device;
import com.qrback.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/devices")
public class DeviceController {
    
    @Autowired
    private DeviceService deviceService;
    
    // 获取单个设备
    @GetMapping("/{id}")
    public ResponseEntity<?> getDeviceById(@PathVariable Integer id) {
        try {
            Device device = deviceService.getDeviceById(id);
            
            // 构建响应对象
            Map<String, Object> response = new HashMap<>();
            response.put("device", device);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
        }
    }
    
    // 创建新设备
    @PostMapping
    public ResponseEntity<?> createDevice(@RequestBody Device device) {
        try {
            // 简化实现，实际项目中需要从JWT令牌中获取当前用户ID
            Integer currentUserId = 1; // 模拟当前用户ID
            Device createdDevice = deviceService.createDevice(device, currentUserId);
            return ResponseEntity.status(HttpStatus.CREATED).body(createdDevice);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        }
    }
    
    // 更新设备信息
    @PutMapping("/{id}")
    public ResponseEntity<?> updateDevice(@PathVariable Integer id, @RequestBody Device device) {
        try {
            device.setId(id); // 确保设备ID正确
            Device updatedDevice = deviceService.updateDevice(device);
            return ResponseEntity.ok(updatedDevice);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        }
    }
    
    // 删除设备
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteDevice(@PathVariable Integer id) {
        try {
            deviceService.deleteDevice(id);
            return ResponseEntity.noContent().build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
        }
    }
    
    // 根据条件筛选设备
    @GetMapping
    public ResponseEntity<?> getAllDevices(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String deviceType,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            // 创建筛选条件Map
            Map<String, Object> filters = new HashMap<>();
            if (keyword != null && !keyword.isEmpty()) {
                filters.put("keyword", keyword);
            }
            if (deviceType != null && !deviceType.isEmpty()) {
                filters.put("deviceType", deviceType);
            }
            if (startDate != null && !startDate.isEmpty()) {
                filters.put("startDate", startDate);
            }
            if (endDate != null && !endDate.isEmpty()) {
                filters.put("endDate", endDate);
            }
            
            List<Device> devices;
            
            // 如果有筛选条件，则使用筛选方法
            if (!filters.isEmpty()) {
                devices = deviceService.filterDevices(filters);
            } else {
                // 否则获取所有设备
                devices = deviceService.getAllDevices();
            }
            
            // 实现分页逻辑
            int total = devices.size();
            int startIndex = (page - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, total);
            List<Device> paginatedDevices;
            
            if (startIndex >= total) {
                paginatedDevices = new ArrayList<>();
            } else {
                paginatedDevices = devices.subList(startIndex, endIndex);
            }
            
            // 构建响应对象，包含设备列表、总数、页码和每页数量
            Map<String, Object> response = new HashMap<>();
            response.put("devices", paginatedDevices);
            response.put("total", total);
            response.put("page", page);
            response.put("pageSize", pageSize);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }
    
    // 生成设备二维码
    @PostMapping("/{id}/qr-code")
    public ResponseEntity<?> generateQrCode(@PathVariable Integer id) {
        try {
            String qrCodePath = deviceService.generateDeviceQrCode(id);
            return ResponseEntity.ok("二维码生成成功，路径：" + qrCodePath);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }
    
    // 导出设备信息为Excel
    @GetMapping("/export/excel")
    public ResponseEntity<?> exportDevicesToExcel(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String deviceType,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            // 创建筛选条件Map
            Map<String, Object> filters = new HashMap<>();
            if (keyword != null && !keyword.isEmpty()) {
                filters.put("keyword", keyword);
            }
            if (deviceType != null && !deviceType.isEmpty()) {
                filters.put("deviceType", deviceType);
            }
            if (startDate != null && !startDate.isEmpty()) {
                filters.put("startDate", startDate);
            }
            if (endDate != null && !endDate.isEmpty()) {
                filters.put("endDate", endDate);
            }
            
            // 获取要导出的设备列表
            List<Device> devices;
            if (!filters.isEmpty()) {
                devices = deviceService.filterDevices(filters);
            } else {
                devices = deviceService.getAllDevices();
            }
            
            // 导出到Excel
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            deviceService.exportDevicesToExcel(outputStream, devices);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "设备信息导出.xlsx");
            
            return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.OK);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }
}